/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.reader.web;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.persistence.Result;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.reader.entity.Reader;
import com.thinkgem.jeesite.modules.reader.entity.ReaderRoler;
import com.thinkgem.jeesite.modules.reader.service.ReaderRolerService;
import com.thinkgem.jeesite.modules.reader.service.ReadersService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 读者管理Controller
 * @author ThinkGem
 * @version 2013-8-29
 */
@Controller
@RequestMapping(value = "${adminPath}/book/reader")
public class ReaderController extends BaseController {

	@Autowired
	private ReadersService readerService;


	@Autowired
	private ReaderRolerService readerRolerService;

	@ModelAttribute
	public Reader get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return readerService.getUser(id);
		}else{
			return new Reader();
		}
	}


	/**
	 * 读者列表
	 * @param reader
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("book:reader:view")
	@RequestMapping(value = {"list", ""})
	public String list(Reader reader, HttpServletRequest request, HttpServletResponse response, Model model,ReaderRoler readerRoler) {
		Page<Reader> page = readerService.findUser(new Page<>(request, response), reader);

		model.addAttribute("page", page);

		Page<ReaderRoler> readerRolerPage = readerRolerService.findUser(new Page<>(request, response), readerRoler);

		model.addAttribute("readerRolerPage", readerRolerPage);

		return "modules/reader/readerList";
	}

	/**
	 * 读者弹窗列表
	 * @param reader
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("book:reader:view")
	@RequestMapping(value = {"listData"})
	public String listData(Reader reader, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Reader> page = readerService.findUser(new Page<>(request, response), reader);
		model.addAttribute("page", page);
		return "modules/reader/readerListData";
	}
	/**
	 * 获取读者信息返回json串
	 */
	@ResponseBody
	@RequestMapping(value = "getReaderInfoBySn")
	public Reader getReaderInfoBySn(@RequestParam(required=true) String readerCardNo){
		return readerService.getReaderInfoBySn(readerCardNo);
	}

	/**
	 * 读者添加页面
	 * @param reader
	 * @param model
	 * @return
	 */
	@RequiresPermissions("book:reader:view")
	@RequestMapping(value = "form")
	public String form(Reader reader, Model model,ReaderRoler readerRoler, HttpServletRequest request, HttpServletResponse response) {

		Page<ReaderRoler> page = readerRolerService.findUser(new Page<>(request, response), readerRoler);

		model.addAttribute("page", page);

		model.addAttribute("reader", reader);

		return "modules/reader/readerForm";
	}


	/**
	 * 读者保存
	 * @param reader
	 * @param request
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("book:reader:edit")
	@RequestMapping(value = "save")
	public String save(Reader reader, RedirectAttributes redirectAttributes){
		readerService.saveReader(reader);
		addMessage(redirectAttributes, "保存用户'" + reader.getRdId() + "'成功");
		return "redirect:" + adminPath + "/book/reader/list?repage";
	}

	/**
	 * 读者删除
	 * @param reader
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("book:reader:edit")
	@RequestMapping(value = "delete")
	public String delete(Reader reader, RedirectAttributes redirectAttributes) {
			readerService.deleteReader(reader);
			addMessage(redirectAttributes, "删除用户成功");
		return "redirect:" + adminPath + "/book/reader/list?repage";
	}

	/**
	 * 导出
	 * @param reader
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("book:reader:edit")
	@RequestMapping(value = "export", method=RequestMethod.POST)
	public String exportFile(Reader reader, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "读者数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
			Page<Reader> page = readerService.findUser(new Page<Reader>(request, response, -1), reader);
			new ExportExcel("读者数据", Reader.class).setDataList(page.getList()).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出读者失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/book/reader/list?repage";
	}

	/**
	 * 导入
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("book:reader:edit")
	@RequestMapping(value = "import", method=RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes){
		try{
			// 导入批次
			String rdPc = Long.toString(System.currentTimeMillis());

			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			List<Reader> list = new ImportExcel(file, 1, 0).getDataList(Reader.class);
			for(Reader reader : list){
				try{
					reader.setRdPc(rdPc);
					Result result = readerService.importReader(reader);
					if(result.success()){
						successNum++;
					}
					else{
						failureNum++;
						failureMsg.append(result.getMsg());
					}
				}
				catch(Exception ex){
					failureNum++;
					failureMsg.append("<br/>编号 " + reader.getRdId() + " 导入失败：" + ex.getMessage());
				}
			}
			if(failureNum > 0){
				failureMsg.insert(0, "，失败 " + failureNum + " 条用户，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 " + successNum + " 条用户" + failureMsg);
		}
		catch(Exception e){
			addMessage(redirectAttributes, "导入用户失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + adminPath + "/book/reader/list?repage";
	}

	/**
	 * 下载模板
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("book:reader:view")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "读者数据导入模板.xlsx";
			List<Reader> list = Lists.newArrayList();
			new ExportExcel("读者数据", Reader.class, 2).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/book/reader/list?repage";
	}

	/**
	 * 读者状态修改
	 * @param reader
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("book:reader:edit")
	@RequestMapping(value = "changestatus")
	public String changeStatus(String status,String id, RedirectAttributes redirectAttributes) {

		if("1".equals(status) || "2".equals(status)){
			Reader reader = new Reader();
			reader.setRdId(id);
			reader.setRdState(status);
			readerService.changeStatus(reader);
			addMessage(redirectAttributes, "变更用户成功！");

		}
		return "redirect:" + adminPath + "/book/reader/list?repage";
	}

}
